package com.voute.View.Activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.umeng.analytics.MobclickAgent;
import com.voute.App.App;
import com.voute.Base.BaseActivity;
import com.voute.Consts.Constants;
import com.voute.Model.Bean.BaseBean;
import com.voute.Model.Bean.UploadImgResponseBean;
import com.voute.Model.IUploadFileModel;
import com.voute.Model.Impl.UploadFileModelImpl;
import com.voute.Presenter.IPostCommentPresenter;
import com.voute.Presenter.Impl.PostCommentPresenterImpl;
import com.voute.R;
import com.voute.Utils.CommonSubscriber;
import com.voute.Utils.FileUtils;
import com.voute.Utils.GlideUtils;
import com.voute.Utils.RetrofitUploadFileParameterBuilder;
import com.voute.Utils.TransformUtils;
import com.voute.View.IView.IPostCommentView;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import okhttp3.RequestBody;

/**
 * 发布评论的activity
 * Created by liucxu on 2017/1/25.
 */

public class PostCommentsActivity extends BaseActivity implements IPostCommentView {
    private RelativeLayout back_layout;
    private TextView publish_tv;
    private EditText feed_comment_edt;
    private TextView remain_text_num_tv;
    private ImageView feed_imv;
    private MaterialDialog progressDialog;
    private String cature_url = "";
    private String pic_url = "";
    private String fid = "";
    private boolean is_positive = true;
    private IPostCommentPresenter presenter;
    private static final int REQUEST_CODE_PICK_IMAGE = 0x01;
    private static final int REQUEST_CODE_TAKE_PHOTO = 0x02;

    @Override
    public int getLayoutId() {
        return R.layout.activity_post_comments;
    }

    @Override
    public void setupView() {
        Intent intent = getIntent();
        fid = intent.getStringExtra("key_fid");
        is_positive = intent.getBooleanExtra("key_positive", true);
        if (TextUtils.isEmpty(fid)) {
            this.finish();
        }
        back_layout = $(R.id.back_layout);
        presenter = new PostCommentPresenterImpl(this);
        publish_tv = $(R.id.publish_tv);
        publish_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (checkValidate()) {
                    String side = "1";
                    if (is_positive) {
                        side = "1";
                    } else {
                        side = "0";
                    }
                    publish_tv.setEnabled(false);
                    presenter.postComment(fid, feed_comment_edt.getText().toString(), side, pic_url);
                }
            }
        });
        feed_comment_edt = $(R.id.feed_comment_edt);
        feed_comment_edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String content = editable.toString();
                if(content.length()>4){
                    publish_tv.setTextColor(Color.parseColor("#fd3768"));
                    publish_tv.setEnabled(true);
                }
                else{
                    publish_tv.setTextColor(Color.parseColor("#a0a0a0"));
                    publish_tv.setEnabled(false);
                }
            }
        });
        remain_text_num_tv = $(R.id.remain_text_num_tv);
        feed_imv = $(R.id.feed_imv);
        back_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PostCommentsActivity.this.finish();
            }
        });
        feed_imv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new MaterialDialog.Builder(PostCommentsActivity.this)
                        .title("选择图片")
                        .items("相册选择", "拍摄照片")
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                                if (position == 0) {
                                    Intent intent = new Intent(Intent.ACTION_PICK);
                                    intent.setType("image/*");
                                    startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                                } else if (position == 1) {
//                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                                    take_photo_uri = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + Constants.IMAGE_URL + ((new Date()).getTime())+".jpg");
//                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, take_photo_uri);
//                                    startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
                                    String savePath = "";
                                    // 判断是否挂载了SD卡
                                    String storageState = Environment
                                            .getExternalStorageState();
                                    if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                                        savePath = Environment
                                                .getExternalStorageDirectory()
                                                .getAbsolutePath()
                                                + Constants.IMAGE_URL;// 存放照片的文件夹
                                        File savedir = new File(savePath);
                                        if (!savedir.exists()) {
                                            savedir.mkdirs();
                                        }
                                    } else {
                                        Toast.makeText(getApplicationContext(), "无法保存照片，请检查SD卡是否挂载", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                                    String fileName = "voute_" + timeStamp + ".jpg";// 照片命名
                                    File out = new File(savePath, fileName);
                                    Uri uri = Uri.fromFile(out);
                                    cature_url = savePath + fileName;// 该照片的绝对路径
                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                                    startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
                                }
                            }
                        })
                        .show();
            }
        });
    }

    @Override
    public void setupData() {

    }

    @Override
    public void postCommentSuccess(BaseBean response) {
        MobclickAgent.onEvent(this, "comment_feed");
        publish_tv.setEnabled(true);
        Toast.makeText(this, "评论成功", Toast.LENGTH_SHORT).show();
        App.GetInstance().finishActivity(this);
    }

    @Override
    public boolean checkValidate() {
        if (TextUtils.isEmpty(feed_comment_edt.getText().toString())) {
//            Snackbar.make(back_layout, "请输入评论内容", Snackbar.LENGTH_SHORT).show();
            MaterialDialog notice_dialog = new MaterialDialog.Builder(PostCommentsActivity.this).title("提示").positiveText("确认").cancelable(false).content("请输入评论内容").build();
            notice_dialog.show();
            return false;
        }
        if (feed_comment_edt.getText().toString().length() < 5) {
            MaterialDialog notice_dialog = new MaterialDialog.Builder(PostCommentsActivity.this).title("提示").positiveText("确认").cancelable(false).content("请输入不少于4字的评论").build();
            notice_dialog.show();
            return false;
        }
//        if(TextUtils.isEmpty(pic_url)){
//            Snackbar.make(back_layout, "请", Snackbar.LENGTH_SHORT).show();
//            return false;
//        }
        return true;
    }

    @Override
    public void showLoading() {
        if (progressDialog == null) {
            progressDialog = new MaterialDialog.Builder(this)
                    .progress(true, 0)
                    .title("提示")
                    .content("请等待...")
                    .autoDismiss(false)
                    .cancelable(true)
                    .build();
        }
        progressDialog.show();
    }

    @Override
    public void hideLoading() {
        progressDialog.dismiss();
    }

    @Override
    public void showError(String errMsg) {
//        Snackbar.make(back_layout, errMsg, Snackbar.LENGTH_SHORT).show();
        publish_tv.setEnabled(true);
        MaterialDialog notice_dialog = new MaterialDialog.Builder(PostCommentsActivity.this).title("提示").positiveText("确认").cancelable(false).content(errMsg).build();
        notice_dialog.show();
    }

    private void startCropActivity(@NonNull Uri uri) {
        String destinationFileName = ((new Date()).getTime() + "");
        UCrop uCrop = UCrop.of(uri, Uri.fromFile(new File(getCacheDir(), destinationFileName + ".jpg")));
        uCrop = ucropConfig(uCrop);
        uCrop.start(PostCommentsActivity.this);
    }

    private UCrop ucropConfig(@NonNull UCrop uCrop) {
        uCrop = uCrop.withAspectRatio(16, 9);
        UCrop.Options options = new UCrop.Options();
        options.setHideBottomControls(false);
        return uCrop.withOptions(options);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            if (data == null) {
                return;
            }
            Uri uri = data.getData();
            startCropActivity(uri);
        }
        if (requestCode == REQUEST_CODE_TAKE_PHOTO) {
            if (!new File(cature_url).exists()) {
                return;
            }
            startCropActivity(Uri.fromFile(new File(cature_url)));
        }
        if (requestCode == UCrop.REQUEST_CROP) {
            showLoading();
            Uri resultUri = UCrop.getOutput(data);
            File uoload_file = FileUtils.getFileByUri(resultUri);
            RetrofitUploadFileParameterBuilder.newBuilder().cleanParams();
            Map<String, RequestBody> params = RetrofitUploadFileParameterBuilder.newBuilder()
                    .addParameter("ftype", "comment")
                    .addParameter("wsfile", uoload_file)
                    .bulider();
            IUploadFileModel model = new UploadFileModelImpl();
            model.uploadImage("https://up.5miaoapp.com/job", params).compose(TransformUtils.<UploadImgResponseBean>defaultSchedulers()).subscribe(new CommonSubscriber<UploadImgResponseBean>() {
                @Override
                public void onSuccess(UploadImgResponseBean response) {
                    hideLoading();
                    pic_url = response.getData().getBaseurl() + "_600.jpg";
                    GlideUtils.getInstance().loadSimpleContextVitMap(PostCommentsActivity.this, pic_url, feed_imv);
                }

                @Override
                public void onFailure(BaseBean response) {
                    hideLoading();
                    pic_url = "";
                }
            });
        }
    }
}
